package com.warm.pump.module.sys.service.impl;

import com.warm.pump.module.sys.bean.po.gen.SysUserRole;
import com.warm.pump.module.sys.dao.gen.SysUserBoDao;
import com.warm.pump.module.sys.dao.gen.SysUserRoleDao;
import com.warm.pump.module.sys.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户与角色对应关系实现类

 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl implements ISysUserRoleService {
	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@Autowired
	private SysUserBoDao sysUserBoDao;

	/**
	 * 根据用户ID和角色ID列表，持久化用户与角色对应关系
	 */
	@Transactional
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
//		if (roleIdList.size() == 0) {
//			return;
//		}

		Map<String,Object> deleteMap = new HashMap<>();
		deleteMap.put("userId",userId);
		// 先删除用户与角色关系
		sysUserRoleDao.deleteByMap(deleteMap);

		// 保存用户与角色关系
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("roleIdList", roleIdList);


		for(long roleId:roleIdList){
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(roleId);
			sysUserRoleDao.insertSelective(userRole);
		}

	}

	/**
	 * 根据用户ID，获取角色ID列表
	 */
	public List<Long> queryRoleIdList(Long userId) {
		Map<String,Object> condMap = new HashMap<>();
		condMap.put("userId",userId);
		return sysUserBoDao.queryRoleIdList(condMap);
	}

	/**
	 * 根据用户ID，删除对应关系
	 */
	public void delete(Long userId) {
		Map<String,Object> condMap = new HashMap<>();
		condMap.put("userId",userId);
		sysUserRoleDao.deleteByMap(condMap);
	}
}
